﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace Xmef.Library
{
    public static class GZipStreamHelper
    {
        private static byte[] GetStreamBytes(Stream stream) 
        { 
            int count = 0; 
            List<byte> result = new List<byte>(); 
            try 
            { 
                byte[] buffer = new byte[0x20000]; 
                int bytes = 0; 
                while ((bytes = stream.Read(buffer, 0, 0x20000)) > 0) 
                { 
                    count += bytes; 
                    for (int i = 0; i < bytes; i++) 
                    { 
                        result.Add(buffer[i]); 
                    } 
                } 
            } 
            catch (Exception ex) 
            { 
                LogHelper.WriteErrorSync(ex); 
                return null; 
            } 
            return result.ToArray(); 
        }

        public static byte[] Compress(byte[] bytes) 
        { 
            using (MemoryStream ms = new MemoryStream()) 
            { 
                using (GZipStream gs = new GZipStream(ms, CompressionMode.Compress, true)) 
                { 
                    gs.Write(bytes, 0, bytes.Length); 
                } 
                ms.Position = 0L;
                return GetStreamBytes(ms); 
            } 
        }

        public static byte[] Decompress(byte[] bytes) 
        { 
            byte[] result; 
            using (MemoryStream ms = new MemoryStream()) 
            { 
                ms.Write(bytes, 0, bytes.Length); 
                using (GZipStream gs = new GZipStream(ms, CompressionMode.Decompress, true)) 
                { 
                    ms.Position = 0L;
                    result = GetStreamBytes(gs); 
                } 
            } 
            return result; 
        }

        public static byte[] CompressString(string data)
        {
            return Compress(Encoding.UTF8.GetBytes(data));
        }

        public static byte[] CompressString(string data, Encoding encoding)
        {
            return Compress(encoding.GetBytes(data));
        }

        public static string DecompressString(byte[] data)
        {
            return Encoding.UTF8.GetString(Decompress(data));
        }

        public static string DecompressString(byte[] data, Encoding encoding)
        {
            return encoding.GetString(Decompress(data));
        }
    }
}
